<?php

namespace App\Http\Controllers\Api\V1;

use Illuminate\Http\Request;
use App\Http\Requests\Api\V1\UserRequest;
use App\Http\Requests\Api\V1\WeappUserRequest;

use App\Models\User;

use App\Http\Resources\V1\UserResource;

use EasyWeChat;
use Auth;

use App\Exceptions\CustomException;

class UsersController extends Controller
{
    public function me(Request $request)
    {
        return new UserResource($request->user());
    }

    public function store(UserRequest $request)
    {
        $user = User::create([
            'name' => $request->name,
            'phone' => $request->phone,
            'password' => $request->password,
        ]);

        return new UserResource($user);
    }

    public function weappStore(WeappUserRequest $request)
    {
        $code = $request->code;

        // 根据 code 获取微信 openid 和 session_key
        $miniProgram = EasyWeChat::miniProgram();
        $data = $miniProgram->auth->session($code);

        if (isset($data['errcode'])) {
            throw new CustomException('code 不正确', 4003);
        }

        $userData = $miniProgram->encryptor->decryptData($data['session_key'], $request->iv, $request->encryptedData);

        // 找到 openid 对应的用户
        $user = User::where('weapp_openid', $data['openid'])->first();

        $attributes['weixin_session_key'] = $data['session_key'];

        $attributes['avatar'] = $userData['avatarUrl'];

        $attributes['weapp_data'] = $userData;

        $attributes['name'] = $userData['nickName'];

        if (!$user) {
            $attributes['weapp_openid'] = $data['openid'];

            $user = User::create($attributes);
        }else{
            // 更新用户数据
            $user->update($attributes);
        }

        // 为对应用户创建 JWT
        $token = auth('api')->login($user);

        return $this->respondWithToken($token)->setStatusCode(201);
    }

    protected function respondWithToken($token)
    {
        return response()->json([
            'access_token' => $token,
            'token_type' => 'Bearer',
            'expires_in' => Auth::guard('api')->factory()->getTTL() * 60,
            'status'     => 0,
        ]);
    }
}
